package _21_多线程._1115_交替打印FooBar;

import java.util.concurrent.atomic.AtomicInteger;

public class _1115_交替打印FooBar {

    private int n;

    private final Object lock = new Object();

    int flag;

    public _1115_交替打印FooBar(int n) {
        this.n = n;
    }

    public void foo(Runnable printFoo) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            synchronized (lock) {
                if ((flag & 1) != 0) {
                    lock.wait();
                }
                // printFoo.run() outputs "foo". Do not change or remove this line.
                printFoo.run();
                flag++;
                lock.notify();
            }
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            synchronized (lock) {
                if ((flag & 1) == 0) {
                    lock.wait();
                }
                // printFoo.run() outputs "foo". Do not change or remove this line.
                printBar.run();
                flag++;
                lock.notify();
            }
        }
    }

}
